﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Web.UI.WebControls;
//using www.SService;
using Controllerss;
using Core.Contract.DataContract;
using www.Controllerss;
using www.Core.Contract.DataContract;

namespace www.Admin
{
    public partial class Category : System.Web.UI.Page
    {
        #region Value
        //   private readonly SServices _services = new SServices();
        private readonly ObjectCache _cache = MemoryCache.Default;
        static bool _insert = false;
        private static List<RelaxCategoryDataContract> _lAdvertiseValue;
        //private readonly HyServicesClient _service = new HyServicesClient();
        private readonly LanguageController _languageController = new LanguageController();
        private readonly CategoryController _categoryController = new CategoryController();
      
        static int _id = 0;
        private static Boolean _insertNew = false;
        #endregion

        #region Contructor

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Convert.ToInt32(Session["role"]) != 1)
            {
                Message("Bạn không đủ quyền để thực hiện chức năng này.");
                Response.Redirect("Default.aspx");
            }

            if (Cache["Language"] == null)
            {
                var lLanguage = _languageController.GetLanguageDataContracts();
                if (lLanguage.Any())
                    Cache.Insert("Language", lLanguage.ToList(), null, DateTime.MaxValue, TimeSpan.FromDays(30));
            }

            if (!IsPostBack)
            {
                var lLanguages = (List<RelaxLanguageDataContract>)Cache["Language"];
                if (lLanguages != null)
                {
                    var lReturn = lLanguages.Where(l => l.Id != 1 && l.Type == 1);
                    Addlist(lReturn);
                }
                LoadCategoryType();
                LoadData();
            }
        }
        #endregion

        #region Event

        protected void lbtinsert_Click(object sender, EventArgs e)
        {
            pnviews.Visible = false;
            pncontrols.Visible = true;
            Donew();
            _insert = true;
            _id = 0;
            _lAdvertiseValue = null;
            grvNgonngu.DataSource = null;
            grvNgonngu.DataBind();
        }

        protected void lbtback_Click(object sender, EventArgs e)
        {
            try
            {
                Back();
            }
            catch (Exception)
            {

            }
        }

        protected void lbtrefresh_Click(object sender, EventArgs e)
        {
            try
            {
                LoadData();
            }
            catch (Exception)
            {

            }

        }

        protected void lbtdel_Click(object sender, EventArgs e)
        {
            try
            {
                Delete();
            }
            catch (Exception)
            {

            }

        }

        protected void grid_advertise_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                grid_Category.PageIndex = e.NewPageIndex;
                LoadData();
            }
            catch (Exception)
            {

            }
        }

        protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadData();
        }

        protected void grid_advertise_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                _id = Convert.ToInt32(e.CommandArgument.ToString());
                var lData = (List<RelaxCategoryDataContract>)_cache["Category"];
                if (lData == null)
                    return;
                var first = lData.FirstOrDefault(p => p.Id == _id && p.Languagecode == 1);
                if (first == null)
                    return;
                if (e.CommandName == "cmd_edit")
                {

                    txtname.Value = first.Name;
                    txtdecription.Value = first.Decription;
                    txtKeyword.Value = first.Keyword;
                    txtord.Value = first.Ord.ToString();
                    chkactive.Checked = first.Active == 1;
                    ddlType.Value = first.Type.ToString();
                    var lValue = lData.Where(p => p.Id == _id && p.Languagecode != 1).ToList();
                    _lAdvertiseValue = lValue;
                    var lReturn = from c in lValue
                                  select new { c.Active, c.Decription, c.Id, c.Keyword, c.Languagecode, c.Name, c.Ord, c.Tag };

                    grvNgonngu.DataSource = lReturn.ToList();
                    grvNgonngu.DataBind();

                    pncontrols.Visible = true;
                    pnviews.Visible = false;
                    _insert = false;

                }
                else if (e.CommandName == "cmd_delete")
                {

                    DeleteLanguage(Convert.ToInt32(Session["LanguageCode"]));

                    lData.Remove(first);
                    _cache["Category"] = lData;
                    LoadData();
                    Message("Xóa Thành Công");
                    _id = 0;
                    _lAdvertiseValue = null;

                }
                else if (e.CommandName == "cmd_active")
                {
                    first.Active = first.Active == 1 ? 0 : 1;

                    if (_categoryController.Update(new List<RelaxCategoryDataContract> {first}))
                    {
                        _cache["Category"] = lData;
                        LoadData();
                        Message("Cập nhật Thành Công");
                        _id = 0;
                        _lAdvertiseValue = null;
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        protected void grvNgonngu_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                var languageCode = e.CommandArgument.ToString();

                if (e.CommandName == "cmd_edit")
                {
                    EditLanguage(Convert.ToInt32(languageCode));
                    _insertNew = true;
                }
                else if (e.CommandName == "cmd_delete")
                {
                    DeleteLanguage(Convert.ToInt32(languageCode));
                }
            }
            catch (Exception)
            {

            }
        }

        protected void lbtsave_Click(object sender, EventArgs e)
        {
            try
            {
                Save();
            }
            catch (Exception)
            {

            }
        }

        protected void lbtdonew_Click(object sender, EventArgs e)
        {
            try
            {
                Donew();
            }
            catch (Exception)
            {

            }

        }

        protected void btnThemValue_Click(object sender, EventArgs e)
        {
            try
            {
                var lData = (List<RelaxCategoryDataContract>)_cache["Category"];
                InsertLanguageCode(lData, _id);
                txtName_Value.Value = txtDecription_Value.Value = txtKeywordValue.Value = string.Empty;
                _insertNew = false;
            }
            catch (Exception)
            {

            }
        }
        #endregion

        #region Business

        private void LoadCategoryType()
        {
            ddlType1.Items.Clear();
            ddlType1.Items.Add(new ListItem("---Chọn---", "0"));
            ddlType.Items.Clear();
            ddlType.Items.Add(new ListItem("---Chọn---", "0"));
            if (_cache["Category"] == null)
            {
                var lData = _categoryController.GetCategoryDataContracts();
                if (lData.Any())
                {
                    var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(27) };
                    _cache.Set("Category", lData.ToList(), policy);
                }
            }
            var lData1 = (List<RelaxCategoryDataContract>)_cache["Category"];
            if (lData1 != null)
                foreach (var item in lData1.Where(p => p.Languagecode == 1 && p.Type <= 0))
                {
                    ddlType1.Items.Add(new ListItem(item.Name, item.Id.ToString()));
                    ddlType.Items.Add(new ListItem(item.Name, item.Id.ToString()));
                }
        }

        private void Addlist(IEnumerable<RelaxLanguageDataContract> lLanguageDataContracts)
        {
            ddlLanguage.Items.Clear();
            ddlLanguage.Items.Add(new ListItem("---Chọn---", "0"));
            foreach (var item in lLanguageDataContracts)
            {
                var items = new ListItem(item.Name, item.Id.ToString());
                ddlLanguage.Items.Add(items);
            }

        }
        private void InsertLanguageCode(IEnumerable<RelaxCategoryDataContract> lData, int iD = 0)
        {

            if (!string.IsNullOrEmpty(ddlLanguage.Value))
            {
                if (iD > 0)
                {
                    if (_lAdvertiseValue == null)
                    {
                        if (lData != null)
                        {
                            var lVaue =
                                lData.Where(p => p.Id == iD && p.Languagecode != Convert.ToInt32(Session["LanguageCode"])).ToList();
                            if (!lVaue.Any())
                                lVaue = new List<RelaxCategoryDataContract>();
                            _lAdvertiseValue = lVaue;
                        }
                        else
                            _lAdvertiseValue = new List<RelaxCategoryDataContract>();
                    }

                    var languageCode = Convert.ToInt32(ddlLanguage.Value);
                    var check = _lAdvertiseValue.Where(p => p.Languagecode == languageCode).ToList();
                    if (check.Any())
                    {
                        if (_insertNew)
                        {
                            var firstordefault = check.FirstOrDefault();
                            if (firstordefault != null)
                            {
                                firstordefault.Languagecode = languageCode;
                                firstordefault.Name = txtName_Value.Value;
                                firstordefault.Tag = txtName_Value.Value.Replace(' ', '-');
                                firstordefault.Decription = txtDecription_Value.Value;
                                firstordefault.Keyword = txtKeywordValue.Value;
                            }
                        }
                        else
                        {
                            Message("Ngôn ngữ này đã tồn tại.");
                            return;
                        }
                    }
                    else
                    {
                        var advertise = new RelaxCategoryDataContract
                        {
                            Id = _id,
                            Languagecode = languageCode,
                            Name = txtName_Value.Value,
                            Tag = txtName_Value.Value.Replace(' ', '-'),
                            Decription = txtDecription_Value.Value,
                            Keyword = txtKeywordValue.Value
                        };
                        _lAdvertiseValue.Add(advertise);
                    }

                }
                else
                {
                    if (_lAdvertiseValue == null)
                        _lAdvertiseValue = new List<RelaxCategoryDataContract>();

                    var languageCode = Convert.ToInt32(ddlLanguage.Value);
                    var check = _lAdvertiseValue.Where(p => p.Languagecode == languageCode).ToList();
                    if (check.Any())
                    {
                        if (_insertNew)
                        {
                            var firstordefault = check.FirstOrDefault();
                            if (firstordefault != null)
                            {
                                firstordefault.Languagecode = languageCode;
                                firstordefault.Name = txtName_Value.Value;
                                firstordefault.Tag = txtName_Value.Value.Replace(' ', '-');
                                firstordefault.Decription = txtDecription_Value.Value;
                                firstordefault.Keyword = txtKeywordValue.Value;
                            }
                        }
                        else
                        {
                            Message("Ngôn ngữ này đã tồn tại.");
                            return;
                        }
                    }
                    else
                    {
                        var advertise = new RelaxCategoryDataContract
                        {
                            Id = _id,
                            Languagecode = languageCode,
                            Name = txtName_Value.Value,
                            Tag = txtName_Value.Value.Replace(' ', '-'),
                            Decription = txtDecription_Value.Value,
                            Keyword = txtKeywordValue.Value
                        };
                        _lAdvertiseValue.Add(advertise);
                    }

                }
                grvNgonngu.DataSource = _lAdvertiseValue;
                grvNgonngu.DataBind();

            }
            else
            {
                Message("Bạn phải chọn ngôn ngữ.");
            }
        }

        private void EditLanguage(int iLanguageCode)
        {
            if (iLanguageCode <= 0) return;
            var first = _lAdvertiseValue.FirstOrDefault(p => p.Languagecode == iLanguageCode);
            if (first != null)
            {
                txtName_Value.Value = first.Name;
                txtDecription_Value.Value = first.Decription;
                txtKeywordValue.Value = first.Keyword;
                ddlLanguage.Value = first.Languagecode.ToString();
            }
        }
        private void DeleteLanguage(int iLanguageCode)
        {

            if (iLanguageCode <= 0) return;

            if (_id > 0)
            {
                _categoryController.Delete(new List<long> { _id }, iLanguageCode);
                if (_lAdvertiseValue != null)
                {
                    var first = _lAdvertiseValue.FirstOrDefault(p => p.Languagecode == iLanguageCode);
                    _lAdvertiseValue.Remove(first);
                }
            }
            else
            {
                if (_lAdvertiseValue != null)
                {
                    var first = _lAdvertiseValue.FirstOrDefault(p => p.Languagecode == iLanguageCode);
                    _lAdvertiseValue.Remove(first);
                }
            }
            grvNgonngu.DataSource = _lAdvertiseValue;
            grvNgonngu.DataBind();
        }
        private void Save()
        {
            try
            {
                if (string.IsNullOrEmpty(txtname.Value) ||
                    string.IsNullOrEmpty(txtord.Value) || string.IsNullOrEmpty(txtdecription.Value))
                {
                    Message("Bạn phải nhập đầy đủ thông tin gợi ý trên");
                    return;
                }
                var lData = (List<RelaxCategoryDataContract>)_cache["Category"];

                var ac = chkactive.Checked ? 1 : 0;

                if (!_insert)
                {
                    var lUpdate = new List<RelaxCategoryDataContract>();
                    if (lData == null)
                        return;
                    var first =
                        lData.FirstOrDefault(p => p.Id == _id && p.Languagecode == 1);
                    if (first == null)
                        return;

                    var advertise = new RelaxCategoryDataContract
                    {
                        Id = _id,
                        Active = ac,
                        Ord = string.IsNullOrEmpty(txtord.Value) ? 0 : Convert.ToInt32(txtord.Value),
                        Keyword = txtKeyword.Value,
                        Name = txtname.Value,
                        Tag = txtname.Value.Replace(' ', '-'),
                        Decription = txtdecription.Value,
                        Languagecode = 1
                    };
                    if (!string.IsNullOrEmpty(ddlType.Value) && Convert.ToInt32(ddlType.Value) > 0)
                        advertise.Type = Convert.ToInt32(ddlType.Value);

                    lUpdate.Add(advertise);

                    if (_lAdvertiseValue.Count > 0)
                    {
                        lUpdate.AddRange(_lAdvertiseValue);
                    }
                    if (_categoryController.Update(lUpdate))
                    {

                        foreach (var item in lUpdate)
                        {
                            var firstordefault = lData.FirstOrDefault(p => p.Id == item.Id && p.Languagecode == item.Languagecode);
                            if (firstordefault != null)
                            {
                                firstordefault.Name = item.Name;
                                firstordefault.Tag = item.Tag;
                                firstordefault.Ord = lUpdate[0].Ord;
                                firstordefault.Keyword = item.Keyword;
                                firstordefault.Decription = item.Decription;
                                firstordefault.Active = lUpdate[0].Active;
                                first.Type = lUpdate[0].Type;
                            }
                            else
                            {
                                item.Id = lUpdate[0].Id;
                                item.Ord = lUpdate[0].Ord;
                                item.Active = lUpdate[0].Active;
                                item.Type = lUpdate[0].Type;
                                lData.Add(item);
                            }
                        }

                        _cache["Category"] = lData;
                        Message("Sửa Thành Công !");
                        _id = 0;
                        _lAdvertiseValue = null;
                        pncontrols.Visible = false;
                        pnviews.Visible = true;
                        LoadCategoryType();
                    }

                }
                else
                {
                    var lAdd = new List<RelaxCategoryDataContract>();
                    var advertise = new RelaxCategoryDataContract
                    {
                        Active = ac,
                        Name = txtname.Value,
                        Tag = txtname.Value.Replace(' ', '-'),
                        Decription = txtdecription.Value,
                        Ord = string.IsNullOrEmpty(txtord.Value) ? 0 : Convert.ToInt32(txtord.Value),
                        Keyword = txtKeyword.Value,
                        Languagecode = 1
                    };
                    if (!string.IsNullOrEmpty(ddlType.Value) && Convert.ToInt32(ddlType.Value) > 0)
                        advertise.Type = Convert.ToInt32(ddlType.Value);

                    lAdd.Add(advertise);
                    if (_lAdvertiseValue != null && _lAdvertiseValue.Count > 0)
                    {
                        lAdd.AddRange(_lAdvertiseValue);
                    }

                    var lId = _categoryController.Add(lAdd);

                    foreach (var item in lAdd)
                    {
                        item.Id = lId;
                        item.Ord = lAdd[0].Ord;
                        item.Active = lAdd[0].Active;
                        item.Type = lAdd[0].Type;
                    }

                    if (lData == null)
                        lData = new List<RelaxCategoryDataContract>();
                    lData.AddRange(lAdd);
                    _cache["Category"] = lData;
                    Message("Thêm Thành Công !");
                    _lAdvertiseValue = null;
                    grvNgonngu.DataSource = null;
                    grvNgonngu.DataBind();
                    LoadCategoryType();
                }
            }
            catch (Exception ex)
            {
                Message(ex.Message);
            }
        }
        private void Back()
        {
            pnviews.Visible = true;
            pncontrols.Visible = false;
            _insert = false;
            _id = 0;
            _lAdvertiseValue = null;
            _insertNew = false;
            LoadData();
        }

        private void Delete()
        {
            try
            {
                if (grid_Category.Rows.Count <= 0) return;
                var hang = 0;
                var lAd = new List<long>();
                for (var i = 0; i < grid_Category.Rows.Count; ++i)
                {
                    var chkselect = ((CheckBox)grid_Category.Rows[i].FindControl("chkselect")).Checked;
                    if (chkselect)
                    {
                        var id = ((Label)grid_Category.Rows[i].FindControl("lblid")).Text;
                        lAd.Add(Convert.ToInt32(id));
                    }
                }
                _categoryController.Delete(lAd, Convert.ToInt32(Session["LanguageCode"]));
                var lData = (List<RelaxCategoryDataContract>)_cache["Category"];
                if ((lData.Any()))
                {
                    foreach (var id in lAd)
                    {
                        var first = lData.FirstOrDefault(p => p.Id == id);
                        if (first != null)
                            lData.Remove(first);
                        hang++;
                    }

                }

                if (hang != 0)
                {
                    Message("Có " + hang + "bản ghi được Xóa Thành Công");
                }
                else
                {
                    Message("Không có bản ghi nào được xóa !");

                }
                LoadData();
            }
            catch { }
        }
        public void LoadData()
        {
            grid_Category.DataSourceID = null;
            var lData = (List<RelaxCategoryDataContract>)_cache["Category"];
            if (lData != null)
            {
                var lReturn = from c in lData.Where(p => p.Languagecode == 1 && p.Type == Convert.ToInt32(ddlType1.SelectedValue))
                              select new { c.Active, c.Decription, c.Id, c.Keyword, c.Languagecode, c.Name, c.Ord, c.Tag, c.Type };
                grid_Category.DataSource = lReturn.ToList();
            }

            grid_Category.DataBind();
        }


        private void Donew()
        {
            chkactive.Checked = false;
            txtdecription.Value = "";
            txtname.Value = "";
            txtName_Value.Value = "";
            txtDecription_Value.Value = "";
            txtord.Value = "";
            txtKeyword.Value = "";
            txtKeywordValue.Value = "";
            txtname.Focus();
        }
        private void Message(string str)
        {
            Response.Write("<script>alert('" + str + "');</script>");
        }
        #endregion

      
    }
}